
import { getExecutable } from '../../common/process/internal/eq';
import { ShellExecFunc } from '../../common/process/types';
import { copyEQExecInfo, EQExecInfo } from '../exec';

export async function getExecutablePath(
    eq: EQExecInfo,
    shellExec: ShellExecFunc,
    timeout?: number,
): Promise<string> {
    const [args, parse] = getExecutable();
    const info = copyEQExecInfo(eq, args);
    const argv = [info.command, ...info.args];
    // Concat these together to make a set of quoted strings
    const quoted = argv.reduce(
        (p, c) => (p ? `${p} ${c.toCommandArgumentForEQExt()}` : `${c.toCommandArgumentForEQExt()}`),
        '',
    );
    const result = await shellExec(quoted, { timeout: timeout ?? 15000 });
    const executable = parse(result.stdout.trim());
    if (executable === '') {
        throw new Error(`${quoted} resulted in empty stdout`);
    }
    return executable;
}